package com.bridge.dict;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;

import java.io.IOException;
import java.util.Objects;
import java.util.Optional;

/**
 * 序列化类
 */
public class DictSerializer extends JsonSerializer<Object> implements ContextualSerializer {

    /**
     * 字典注解
     */
    private Dict dict;


    public DictSerializer() {
    }

    public DictSerializer(Dict dict) {
        this.dict = dict;
    }

    @Override
    public void serialize(Object value, JsonGenerator gen, SerializerProvider provider) throws IOException {
        if (Objects.isNull(dict)) {
            return;
        }
        // 通过数据字典类型和value获取name
        String file = gen.getOutputContext().getCurrentName();

        gen.writeString(value + "");
        gen.writeStringField(gen.getOutputContext().getCurrentName()+"DictName" , value+"DictName");
    }

    @Override
    public JsonSerializer<?> createContextual(SerializerProvider prov, BeanProperty beanProperty) throws JsonMappingException {
        Dict dict = Optional.ofNullable(beanProperty).map(b -> b.getAnnotation(Dict.class)).orElse(null);
        return new DictSerializer(dict);
    }
}
